package com.demo.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: jxm
 * @Description: 解决死锁方法二 ：使用ReentrantLock来代替synchronized关键字
 * @Date: 2024-2-5 15:39
 * @Version: 1.0
 */
public class DeadlockDemo2 {

    private static final ReentrantLock lock1 = new ReentrantLock();
    private static final ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            while (true) {
                if (lock1.tryLock()) {
                    System.out.println("Thread 1 acquired lock1");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (lock2.tryLock()) {
                        System.out.println("Thread 1 acquired lock2");
                        lock2.unlock();
                        break;
                    } else {
                        lock1.unlock();
                    }
                }
            }
            lock1.unlock();
        });

        Thread thread2 = new Thread(() -> {
            while (true) {
                if (lock2.tryLock()) {
                    System.out.println("Thread 2 acquired lock2");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (lock1.tryLock()) {
                        System.out.println("Thread 2 acquired lock1");
                        lock1.unlock();
                        break;
                    } else {
                        lock2.unlock();
                    }
                }
            }
            lock2.unlock();
        });

        thread1.start();
        thread2.start();
    }

}
